package com.bawei.mvidemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 网络封装：
 1：retrofit+okhttp+rxjava   RxJava2CallAdapterFactory
 2：retrofit+okhtttp+viewmodel+livedata LiveDataCallBackFactory
 3：retrofit+okhtttp+viewmodel+协程flow ：




 */
class MainActivity : AppCompatActivity() {
    private lateinit var myViewModel: MyViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
        //5:根据uistate更新UI
        lifecycleScope.launch{
            myViewModel.uiState.collect{
                when(it){
                    is MyUIState.Success -> Toast.makeText(this@MainActivity,"数据请求成功"+it.videoList?.size,Toast.LENGTH_SHORT).show()
                    is MyUIState.Error -> Toast.makeText(this@MainActivity,"数据请求失败"+it.exception.message,Toast.LENGTH_SHORT).show()
                    is MyUIState.Loading -> Toast.makeText(this@MainActivity,"数据加载中",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    //1：发送intent给viewmodel
    fun video(view: View) {
        lifecycleScope.launch{
            myViewModel.newsChannel.send(MyIntent.GetVideos)
        }

    }
}